package com.qinggeng.project.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Maps;
import com.qinggeng.common.enums.CommandTypeEnum;
import com.qinggeng.common.enums.ShowTypeEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.framework.redis.RedisCache;
import com.qinggeng.framework.web.domain.AjaxResult;
import com.qinggeng.project.api.dto.AreaLimitDTO;
import com.qinggeng.project.api.security.annotation.LoginRequired;
import com.qinggeng.project.api.security.utils.ApiUtils;
import com.qinggeng.project.api.utils.CommandUtils;
import com.qinggeng.project.system.domain.vo.UserInvitCodeVO;
import com.qinggeng.project.system.service.ISysConfigService;
import com.qinggeng.project.system.service.UserInvitCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 吴鹏飞
 * @date 2020/11/6
 *
 */
@Api(tags = "口令模块")
@Slf4j
@RestController
@RequestMapping("${apiPath}/command")
public class ApiCommandController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserInvitCodeService userInvitCodeService;

    @Autowired
    private ISysConfigService sysConfigService;


    @ApiOperation("生成口令")
    @GetMapping("/createCommand")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commandType", value = "口令类型 10=捶一捶 20=助力", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "data", value = "数据", dataType = "String", paramType = "query", required = true),
    })
    @CrossOrigin
    public AjaxResult createCommand(String commandType, String data,String adCode) {
        try {
            String command = CommandUtils.getCommand(commandType, data, redisCache,adCode);
            //封装
            HashMap<String, String> map = Maps.newHashMap();
            map.put("command", command);
            return AjaxResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常" + e.getMessage());
        }
    }

    @ApiOperation("解析口令")
    @PostMapping("/parseCommand")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "command", value = "口令", dataType = "String", paramType = "query", required = true),
    })
    @LoginRequired
    @CrossOrigin
    public AjaxResult parseCommand(String command,String adCode) {

            if (StringUtils.isEmpty(command)) {
                return AjaxResult.error("口令不能为空");
            }
            if (StringUtils.isEmpty(adCode)){
                return AjaxResult.error("adCode不能为空");
            }

        String areaListString = (String) sysConfigService.selectConfigByKey("sys.area.limit");
        List<AreaLimitDTO> areaLimitDTOS = JSONArray.parseArray(areaListString, AreaLimitDTO.class);
        if (!CollectionUtils.isEmpty(areaLimitDTOS)){
            areaLimitDTOS = areaLimitDTOS.stream().filter(s -> adCode.equals(s.getAdCode())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(areaLimitDTOS)){
                return AjaxResult.error("对不起,当前地区超出活动范围,无法参加",ShowTypeEnum.用户.getValue());
            }
        }
        //获取加密值
            String key = CommandUtils.parseCommand(command);
            String value = redisCache.getCacheObject(key);
            String[] keys = key.split("_");
            //封装
            Map<String, Object> data = Maps.newHashMap();
            data.put("activityType", keys[1]);
            data.put("command", command);
            //是否是自己的口令 默认不是自己口令
            data.put("isYouSelf", false);


            if (keys[1].equals(CommandTypeEnum.捶一捶.getValue())) {
                if (!keys[2].equals(adCode)){
                    return AjaxResult.error("您的位置不对，只有同城用户才能拉新",ShowTypeEnum.用户.getValue());
                }
                data.put("beatABeat", value);
                data.put("friendAssist", "");
                return AjaxResult.success(data);
            }
            if (keys[1].equals(CommandTypeEnum.好友助力.getValue())) {
                if (!keys[2].equals(adCode)){
                    return AjaxResult.error("您的位置不对，只有同城用户才能拉新",ShowTypeEnum.用户.getValue());
                }
                data.put("beatABeat", "");
                data.put("friendAssist", value);
                return AjaxResult.success(data);
            }
            if (keys[1].equals(CommandTypeEnum.PULL_NEW.getValue())) {
                UserInvitCodeVO userInvitCodeVO=userInvitCodeService.getUserInvitCodeVO(command,adCode);
                if (null ==userInvitCodeVO){
                    throw new CustomException("没有当前口令");
                }
                log.info("token解析用户 {} , 邀请码用户id {}",ApiUtils.getUserId(),userInvitCodeVO.getUserId());
                boolean bl =userInvitCodeVO.getUserId().equals(ApiUtils.getUserId());
                if (bl==false){
                    return AjaxResult.success(data);
                }
                throw new CustomException("当前口令属于自己",ShowTypeEnum.后台.getValue());
            }
        return AjaxResult.error("系统异常");
    }

}
